using UnityEngine;
using UnityEditor;

namespace LCH
{
    /// <summary>
    /// 网格绘制器 - 纹理保存功能模块
    /// </summary>
    public partial class LchMeshPainter
    {
        /// <summary>
        /// 将RenderTexture保存为TGA格式的Texture2D
        /// </summary>
        /// <param name="rt">要保存的RenderTexture</param>
        /// <param name="path">保存路径</param>
        /// <param name="newTexture">是否为新纹理（需要导入）</param>
        /// <returns>保存后的Texture2D</returns>
        private Texture2D SaveRenderTextureToTga(RenderTexture rt, string path, bool newTexture)
        {
            if(null== rt )
                return null;
            RenderTexture prev = RenderTexture.active;
            rt.filterMode = FilterMode.Point;
            RenderTexture.active = rt;
            Texture2D tga = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32,false,true);
            tga.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
            byte[] bytes = LchEncode.EncodeToTGA(tga, 4);
            System.IO.DirectoryInfo topDir = System.IO.Directory.GetParent(path);
            if (!topDir.Exists)
            {
                topDir.Create();
            }
            System.IO.File.WriteAllBytes(path, bytes);
           
            RenderTexture.active = prev;
            rt.filterMode = FilterMode.Bilinear;
            if (newTexture)
                AssetDatabase.ImportAsset(path);
            TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path);
            if (null != importer)
            {
                importer.sRGBTexture = false;
                importer.isReadable = true;
                importer.textureCompression = TextureImporterCompression.CompressedHQ;
                importer.SaveAndReimport();
            }
            
            
            Texture2D t = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
          
            AssetDatabase.SaveAssets();
            Texture2D.DestroyImmediate(tga);
            tga = null;
            return t;
        }

        /// <summary>
        /// 从RenderTexture获取Texture2D
        /// </summary>
        /// <param name="rt">源RenderTexture</param>
        /// <returns>转换后的Texture2D</returns>
        private Texture2D GetTexture2D(RenderTexture rt )
        {
            RenderTexture prev = RenderTexture.active;
            rt.filterMode = FilterMode.Point;
            RenderTexture.active = rt;
            Texture2D tga = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false, true);
            tga.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
            RenderTexture.active = prev;
            return tga;
        }

        /// <summary>
        /// 将Texture2D保存为TGA文件
        /// </summary>
        /// <param name="tga">要保存的Texture2D</param>
        /// <param name="path">保存路径</param>
        /// <param name="newTexture">是否为新纹理（需要导入）</param>
        /// <returns>保存后的Texture2D</returns>
        private Texture2D SaveTexture2DToTga(Texture2D tga, string path, bool newTexture)
        {
 
            byte[] bytes = LchEncode.EncodeToTGA(tga, 4);
            System.IO.DirectoryInfo topDir = System.IO.Directory.GetParent(path);
            if (!topDir.Exists)
            {
                topDir.Create();
            }
            System.IO.File.WriteAllBytes(path, bytes);

            Texture2D.DestroyImmediate(tga);
            tga = null;

            if (newTexture)
                AssetDatabase.ImportAsset(path);
            TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path);
            importer.sRGBTexture = false;
            importer.isReadable = true;
            importer.textureCompression = TextureImporterCompression.CompressedHQ; 
            importer.SaveAndReimport();
            
            Texture2D t = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
          
            AssetDatabase.SaveAssets();
            
            return t;
        }

        /// <summary>
        /// 保存所有控制图和FlowMap纹理
        /// </summary>
        void SaveTextures()
        {
            if (controlTextureCount == 0 || editorCtrl1RT == null)
                return;
                
            string[] _paths = new string[controlTextureCount];
            string flowPath = null;

            // 为所有控制图准备路径
            for (int i = 0; i < controlTextureCount; i++)
            {
                if (null != editorCtrl1RT[i])
                {
                    if (null == ctrlText[i])
                    {
                        if (i == 0)
                        {
                            _paths[0] = EditorUtility.SaveFilePanelInProject("Control Texture " + (i + 1) + " saved position", "ctrl" + (i + 1), "tga", "Where is control texture " + (i + 1) + " saved");
                            if (_paths[0].Length > 0)
                            {
                                // 为其他控制图生成路径
                                for (int j = 1; j < controlTextureCount; j++)
                                {
                                    _paths[j] = _paths[0].Substring(0, _paths[0].Length - 4) + "_ctrl" + (j + 1) + "." + _paths[0].Substring(_paths[0].Length - 3);
                                }
                                flowPath = _paths[0].Substring(0, _paths[0].Length - 4) + "_flow." + _paths[0].Substring(_paths[0].Length - 3);
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                    else
                    {
                        if (i == 0)
                        {
                            _paths[0] = AssetDatabase.GetAssetPath(ctrlText[0]);
                            // 为其他控制图生成路径
                            for (int j = 1; j < controlTextureCount; j++)
                            {
                                _paths[j] = _paths[0].Substring(0, _paths[0].Length - 4) + "_ctrl" + (j + 1) + "." + _paths[0].Substring(_paths[0].Length - 3);
                            }
                            flowPath = _paths[0].Substring(0, _paths[0].Length - 4) + "_flow." + _paths[0].Substring(_paths[0].Length - 3);
                        }
                    }
                }
            }
            
            bool fix = false;
            // 如果有两张或更多控制图，尝试修复通道
            if (controlTextureCount >= 2)
            {
                if(editorCtrl1RT[0])
                    ctrlText[0] = GetTexture2D(editorCtrl1RT[0]);
                if (editorCtrl1RT[1])
                    ctrlText[1] = GetTexture2D(editorCtrl1RT[1]);

                if (null != ctrlText[0] && null != ctrlText[1] && _paths[0] != null && _paths[1] != null)
                {
                    var bs0 = ctrlText[0].GetPixels();
                    var bs1 = ctrlText[1].GetPixels();
                    if (bs0.Length == bs1.Length)
                    {
                        fix = true;
                        for (int i = 0; i < bs0.Length; i++)
                        {
                            var c = bs0[i];
                            var c1 = bs1[i];
                            bs0[i] = new Color(Mathf.Max(1f - (c.g + c.b + c.a + c1.r + c1.g + c1.b + c1.a), 0f), c.g, c.b, c.a);
                        }
                        ctrlText[0].Apply();
                    }

                    ctrlText[0] = SaveTexture2DToTga(ctrlText[0], _paths[0], true);
                    ctrlText[1] = SaveTexture2DToTga(ctrlText[1], _paths[1], true);

                    if (detectedCtrlTextureNames.Count > 0)
                        selectObjectMaterial.SetTexture(detectedCtrlTextureNames[0], ctrlText[0]);
                    if (detectedCtrlTextureNames.Count > 1)
                        selectObjectMaterial.SetTexture(detectedCtrlTextureNames[1], ctrlText[1]);
                    Debug.LogError("fixed channel");
                }
            }
                 
            if(!fix)
            {
                // 保存所有控制图
                for (int i = 0; i < controlTextureCount && i < editorCtrl1RT.Length && i < _paths.Length; i++)
                {
                    if (editorCtrl1RT[i] != null)
                    {
                        ctrlText[i] = SaveRenderTextureToTga(editorCtrl1RT[i], _paths[i], null == ctrlText[i]);
                        if (i < detectedCtrlTextureNames.Count)
                            selectObjectMaterial.SetTexture(detectedCtrlTextureNames[i], ctrlText[i]);
                    }
                }
            }
            if (editorFlowMapRT != null && hasFlowMap)
            {
                if (flowMapTex != null)
                    flowPath = AssetDatabase.GetAssetPath(flowMapTex);
                if (null == flowPath || flowPath.Length == 0)
                {
                    flowPath = EditorUtility.SaveFilePanelInProject("flow map saved poisition", " flowmap1", "tga", "Where is channel one saved");
                }
                if (flowPath.Length > 0)
                {
                    flowMapTex = SaveRenderTextureToTga(editorFlowMapRT, flowPath, true);

                    selectObjectMaterial.SetTexture(setting.flowMapTextureName, flowMapTex);
                }
            }
        }
    }
}

